<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺id" prop="shopId" v-if="myDept != '店铺'">
        <el-input
          v-model="queryParams.shopId"
          placeholder="请输入店铺id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入单价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品数量" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入商品数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售卖数量" prop="salenum">
        <el-input
          v-model="queryParams.salenum"
          placeholder="请输入售卖数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入商品描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品信息" prop="information">
        <el-input
          v-model="queryParams.information"
          placeholder="请输入商品信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="myDept == '店铺'">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['backstage:goodsinfo:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="myDept!='店铺'">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="true"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="myDept == '店铺'">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['backstage:goodsinfo:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="myDept != '店铺'">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="true"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['backstage:goodsinfo:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['backstage:goodsinfo:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品id" align="center" prop="id"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="店铺id" align="center" prop="shopId"/>
      <el-table-column label="单价" align="center" prop="price"/>
      <el-table-column label="商品数量" align="center" prop="number"/>
      <el-table-column label="售卖数量" align="center" prop="salenum"/>
      <el-table-column label="商品描述" align="center" prop="description"/>
      <el-table-column label="商品信息" align="center" prop="information"/>
      <el-table-column label="商品图片" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.status==1">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="其他操作" align="center" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" plain @click="handleGoodsCategory(scope.row.id)" size="small">类别</el-button>
          <el-button type="primary" plain @click="goodsModelOpen(scope.row.id)" size="small">图片</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="myDept == '店铺'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['backstage:goodsinfo:edit']"
          >修改
          </el-button>
          <el-button v-if="scope.row.status == 0"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['backstage:goodsinfo:remove']"
          >下架
          </el-button>

          <el-button v-if="scope.row.status == 1"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleAlter(scope.row)"
          >上架
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="店铺id" prop="shopId" v-show="myDept != '店铺'">
          <el-input v-model="form.shopId" placeholder="请输入店铺id"/>
        </el-form-item>
        <el-form-item label="店铺id" prop="shopId" v-show="myDept=='店铺'">
          <el-input v-model="form.shopId" :disabled="true" placeholder="请输入店铺id"/>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="商品数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入商品数量"/>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入商品描述"/>
        </el-form-item>
        <el-form-item label="商品信息" prop="information">
          <el-input v-model="form.information" placeholder="请输入商品信息"/>
        </el-form-item>
        <el-form-item label="商品图片">
          <image-upload v-model="form.img"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    商品类别对话框-->
    <el-dialog :title="ctitle" :visible.sync="copen" width="500px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="openGoodsCategory"
          >新增
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="categoryList">
        <el-table-column label="类别id" align="center" prop="id"/>
        <el-table-column label="类别名称" align="center" prop="category.name"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelGoodsCategory(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!--    商品添加相关类别-->
    <el-dialog :title="category" :visible.sync="categoryOpen" width="500px" append-to-body>
      <el-select v-model="categoryId1" placeholder="请选择一级类别" @change="categories">
        <el-option
          v-for="item in c1"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <el-select v-model="categoryId2" placeholder="请选择二级类别">
        <el-option
          v-for="item in c2"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="categoryOpen = false">取 消</el-button>
        <el-button type="primary" @click="addGoodsCategory">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog :title="imgTitle" :visible.sync="goodsOpen" width="500px">
      <my-img-upload v-model="goodsImg"></my-img-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsOpen = false">取 消</el-button>
        <el-button type="primary" @click="updateGoodsImg">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoodsinfo,
  getGoodsinfo,
  delGoodsinfo,
  addGoodsinfo,
  updateGoodsinfo,
  alterGoodsInfo
} from "@/api/backstage/goodsinfo";

import Cookies from "js-cookie";

import {
  getGoodsCategory,
  delGoodsCategory,
  addGoodsCategory
} from "@/api/backstage/goodsCategory";

import {getCategories} from "@/api/backstage/category";

import {
  goodsImgList,
  insertGoodsImg
} from "@/api/backstage/goodsImg";

import {getShopByUid} from '@/api/backstage/shopinfo';

export default {
  name: "Goodsinfo",
  data() {
    return {
      myUID: '',
      myDept: '',
      myShop: {},

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息管理表格数据
      goodsinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        shopId: null,
        price: null,
        number: null,
        salenum: null,
        description: null,
        information: null,
        img: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "商品名称不能为空", trigger: "blur"}
        ],
        shopId: [
          {required: true, message: "店铺id不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "单价不能为空", trigger: "blur"}
        ],
        number: [
          {required: true, message: "商品数量不能为空", trigger: "blur"}
        ],
      },
      //商品类别对话框
      ctitle: "",
      copen: false,
      categoryList: [],
      goodsId: "",

      //类别对话框
      category: "",
      categoryOpen: false,
      c1: [],
      c2: [],
      categoryId1: "",
      categoryId2: "",
      c: {
        goodsId: "",
        categoryId: ""
      },

      //商品图片对话框
      imgTitle: "添加商品图片",
      goodsOpen: false,
      goodsImg: [],
      gImg: {
        id: '',
        img: [],
      }
    };
  },
  created() {
    this.myDept = Cookies.get("myDeptName");
    this.myUID = Cookies.get("myUID");
    if (this.myDept == "店铺") {
      getShopByUid(this.myUID).then(res => {
        this.myShop = res.data;
        this.queryParams.shopId = this.myShop.id;
        console.log(res);
      });
    }

    var that = this;
    setTimeout(function () {
      that.getList();
    }, 500);

  },
  methods: {
    /** 查询商品信息管理列表 */
    getList() {
      this.loading = true;
      listGoodsinfo(this.queryParams).then(response => {
        this.goodsinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      if (this.myDept == '店铺') {
        this.form.shopId = this.myShop.id;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        shopId: null,
        price: null,
        number: null,
        salenum: null,
        description: null,
        information: null,
        img: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if (this.myDept == '店铺') {
        this.form.shopId = this.myShop.id;
      }
      this.open = true;
      this.title = "添加商品信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (this.myDept == '店铺') {
        this.form.shopId = this.myShop.id;
      }
      const id = row.id || this.ids
      getGoodsinfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品信息管理";
        console.log(this.form);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoodsinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认下架商品信息管理编号为"' + ids + '"的数据项？').then(function () {
        return delGoodsinfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("下架成功");
      }).catch(() => {
      });
    },
    handleAlter(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认上架商品信息管理编号为"' + ids + '"的数据项？').then(function () {
        return alterGoodsInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("上架成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('backstage/goodsinfo/export', {
        ...this.queryParams
      }, `goodsinfo_${new Date().getTime()}.xlsx`)
    },
    handleGoodsCategory(id) {
      const gid = id;
      this.goodsId = id;
      getGoodsCategory(gid).then(response => {
        this.ctitle = "商品类别";
        this.copen = true;
        this.categoryList = response.data;
        console.log(this.categoryList);
      });
    },
    handleDelGoodsCategory(row) {
      this.$modal.confirm("确定删除此商品类别吗？").then(function () {
        return delGoodsCategory(row.id);
      }).then(() => {
        this.handleGoodsCategory((row.goodsId));
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    openGoodsCategory() {
      getCategories(1).then(response => {
        const list = response.data;
        this.category = "商品新增类别";
        this.c1 = list;
        this.categoryOpen = true;
      });
    },
    categories() {
      this.categoryId2 = "";
      getCategories(this.categoryId1).then(response => {
        const list = response.data;
        this.c2 = list;
      });
    },
    addGoodsCategory() {
      if (this.goodsId == null || this.goodsId == '') {
        this.$modal.alertWarning("请选择所添加商品");
      }
      if (this.categoryId2 == null || this.categoryId2 == '') {
        this.$modal.alertWarning("请选择所添加商品二级类别");
      }
      this.c.goodsId = this.goodsId;
      this.c.categoryId = this.categoryId2;

      const cList = this.categoryList;
      for (var i = 0; i < cList.length; i++) {
        if (this.categoryId2 == cList[i].category.id) {
          this.$modal.alertWarning("此商品已有该类别标签");
          this.categoryOpen = false;
          return false;
        }
      }

      addGoodsCategory(this.c).then(() => {
        this.$modal.msgSuccess("添加成功");
        this.handleGoodsCategory(this.goodsId);
        this.categoryOpen = false;
      });
    },

    goodsModelOpen(id) {
      this.gImg.id = id;
      goodsImgList(id).then(response => {
        const list = response.data;
        this.gImg.img = [];
        for (var i = 0; i < list.length; i++) {
          this.gImg.img.push(list[i].url);
        }
        this.goodsImg = this.gImg.img;
      })

      this.goodsOpen = true;
    },
    updateGoodsImg() {
      this.gImg.img = this.goodsImg.split(',');
      console.log(this.gImg);
      insertGoodsImg(this.gImg.id, this.gImg.img).then(() => {
        this.$modal.msgSuccess("添加成功");
      });

      this.gImg = {};
    }

  }
};
</script>
